package dukeCE.insightTracker;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import dukeCE.insightTracker.R;
import dukeCE.insightTracker.Classes.topicListItem;
import dukeCE.insightTracker.Classes.topicListAdapter;
import dukeCE.insightTracker.Classes.topicList;

public class home_activity extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_activity);
        
        String exampleJsonInput=null;
        //Connect to server and recive a JSON output
        //Normally we have to send out and $_POST['loginAuth'] to check if the user is valid, but we will get this done later
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://kevin2011.byethost3.com/adr_ch_2.php");
        try {
            // Add your data
        	/*
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("loginAuth", "This should be a hash code"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));*/
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            exampleJsonInput=getStringFromServerResponse(response.getEntity().getContent()).toString();        
        } catch (ClientProtocolException e) {
        	exampleJsonInput="Client error";
        } catch (IOException e) {
        	exampleJsonInput = "IO error";
        }

        
        //---------------------------------------------//
        
        //test the content of topics, these data should be pulling form db
        /*
        exampleJsonInput = "{\"topicCount\":2,\"topicList\":" + exampleJsonInput + "}";*/
        
        
       exampleJsonInput = "{\"topicCount\":6,\"topicList\":[{\"" +
        		"topicId\":1,\"topicName\":\"Json \",\"topicDescription\":\"Gson is awsome\",\"isStarred\":true},{\"" +
        		"topicId\":2,\"topicName\":\"Topic 2\",\"topicDescription\":\"This is a second test\",\"isStarred\":false},{\"" +
        		"topicId\":3,\"topicName\":\"topic test name\",\"topicDescription\":\"This is a third test\",\"isStarred\":false},{\"" +
        		"topicId\":4,\"topicName\":\"Good topic\",\"topicDescription\":\"This is a description\",\"isStarred\":true},{\"" +
        		"topicId\":5,\"topicName\":\"Topic id\",\"topicDescription\":\"A topic id is unique\",\"isStarred\":true},{\"" +
        		"topicId\":6,\"topicName\":\"More data\",\"topicDescription\":\"This is just a test\",\"isStarred\":false}]}";
        
       	fillTheListView(exampleJsonInput,false);
        
        //set listener for sort button
        TextView sortBt = (TextView) findViewById(R.id.sortBt);
        sortBt.setClickable(true);
        final String sortedOutput = exampleJsonInput;
        sortBt.setOnClickListener(new View.OnClickListener() {
        	private boolean isOn = true;
        	@Override
            public void onClick(View v)
            {
        		fillTheListView(sortedOutput,isOn);
        		isOn = !isOn;
            }});


    }
    public void fillTheListView(String inputJson, boolean starredOnly)
    {
    	  Gson gson = new Gson();
          final topicList listTopic= gson.fromJson(inputJson, topicList.class);
          int topicCount = listTopic.getCount();
          ArrayList<topicListItem> items = new ArrayList<topicListItem>();
          
          for(int i =0;i<topicCount;i++)
          {
        	  if(starredOnly!=true)
        		  items.add(new topicListItem(listTopic.getTopicByOrder(i).getTopicID(),listTopic.getTopicByOrder(i).getName(),listTopic.getTopicByOrder(i).getDes(),listTopic.getTopicByOrder(i).isStarred()));
        	  else
        	  {
        		  if(listTopic.getTopicByOrder(i).isStarred()==true)
        		  	items.add(new topicListItem(listTopic.getTopicByOrder(i).getTopicID(),listTopic.getTopicByOrder(i).getName(),listTopic.getTopicByOrder(i).getDes(),listTopic.getTopicByOrder(i).isStarred()));
        	  }
          }
          
          
          final topicListAdapter itemAdapter = new topicListAdapter(getApplicationContext(), R.layout.topic_list_row, items);        
          
          final ListView topicList = (ListView) findViewById(R.id.topicList);
          
          topicList.setAdapter(itemAdapter);
          //Set listView listener
          topicList.setClickable(true);
          topicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  			@Override
  			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
  			{
  				//getTopicID
  				int topicIDrow= itemAdapter.getItem(position).getID();
                  Intent i = new Intent(getApplicationContext(), content_activity.class);
                  i.putExtra("topicID", topicIDrow);
                  startActivity(i);				
  			}
              });
    }
    public void newTopic(View view) {
        Intent i = new Intent(getApplicationContext(), post_activity.class);
        startActivity(i);
    }
    public void profileDlg(View view) {
        Intent i = new Intent(getApplicationContext(), profile_activity.class);
        startActivity(i);
    }
    public void aboutDlg(View view) {
        Intent i = new Intent(getApplicationContext(), about_activity.class);
        startActivity(i);
    }
    
    
    // Read the output of httpresponse
    private StringBuilder getStringFromServerResponse(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        // Read response until the end
        try {
			while ((line = rd.readLine()) != null) { 
			    total.append(line); 
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        // Return full string
        return total;
    }
    //-------------------------------------------

    
}
